package com.gcp.freemarker.service;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AnnotationAdder {

//    public static void main(String[] args) {
//        // 替换为你的Controller类文件路径
//        String filePath = "D:/eco/api_management/src/main/java/com/eco/api/controller/RoleInfoController.java";
//
//        try {
//            addSaCheckPermissionAnnotation(filePath);
//            System.out.println("处理完成！");
//        } catch (IOException e) {
//            System.err.println("处理文件时出错: " + e.getMessage());
//        }
//    }

    /**
     * 在所有的@ApiOperation上加上@SaCheckPermission注解，并赋值为接口路径
     * @param absoluteFilePath 绝对路径
     * @throws IOException
     */
    public static void addSaCheckPermissionAnnotation(String absoluteFilePath) throws IOException {
        Path path = Paths.get(absoluteFilePath);

        // 读取文件内容
        String content = new String(Files.readAllBytes(path));

        // 处理内容
        String processedContent = processControllerContent(content);

        // 写回文件
        Files.write(path, processedContent.getBytes());
    }

    private static String processControllerContent(String content) {
        // 匹配类上的@RequestMapping注解获取基础路径
        String basePath = extractClassLevelRequestMapping(content);

        // 处理每个方法
        StringBuilder result = new StringBuilder();
        String[] lines = content.split("\n");
        for (int i = 0; i < lines.length; i++) {
            String line = lines[i];
            result.append(line).append("\n");
            // 检查是否是@ApiOperation注解行
            if (line.trim().startsWith("@ApiOperation")) {
                // 向下查找方法上的@RequestMapping注解
                String methodPath = findMethodPath(lines, i);
                String fullPath = (basePath + methodPath).replace("/", ":");
                // 在@ApiOperation前插入@SaCheckPermission
                result.insert(result.length() - line.length() - 1,
                        "    @SaCheckPermission(\"" + fullPath.substring(1) + "\")\n");
            }
        }

        return result.toString();
    }

    private static String extractClassLevelRequestMapping(String content) {
        Pattern pattern = Pattern.compile("@RequestMapping\\([\"']([^\"']+)[\"']");
        Matcher matcher = pattern.matcher(content);
        return matcher.find() ? matcher.group(1) : "";
    }

    private static String findMethodPath(String[] lines, int apiOperationLine) {
        // 从@ApiOperation行向上查找方法注解
        for (int i = apiOperationLine + 1; i < apiOperationLine + 2; i++) {
            String line = lines[i].trim();
            if (line.startsWith("@RequestMapping") || line.startsWith("@GetMapping") ||
                    line.startsWith("@PostMapping") || line.startsWith("@PutMapping") ||
                    line.startsWith("@DeleteMapping") || line.startsWith("@PatchMapping")) {

                // 提取路径值
                Matcher matcher = Pattern.compile("[\"']([^\"']+)[\"']").matcher(line);
                return matcher.find() ? matcher.group(1) : "";
            }
        }
        return "";
    }

}
